import React, {useEffect, useState} from "react";
import {Select} from "antd";
import http from "../request";

const { Option } = Select;

const City = (props) => {
    const {value} = props
    const [cityList, setCityList] = useState([])
    const [regionList, setRegionList] = useState([])
    const [areaList, setAreaList] = useState([])

    const [city, setCity] = useState()
    const [region, setRegion] = useState()
    const [area, setArea] = useState()

    useEffect(() => {
        getCity()
        setCity(value[0])
        setRegion(value[1])
        setArea(value[2])
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [value])
    useEffect(() => {
        city && getRegion()
        !city && setRegionList([])
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [city])
    useEffect(() => {
        region && getArea()
        !region && setAreaList([])
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [region])
    return (
        <div className={`u-flex ${props.className}`}>
            <Select value={city} onChange={cityChange} allowClear placeholder="城市" style={{width: 100}}>
                { cityList.map(e => <Option value={e.id} key={e.id}>{e.name}</Option>) }
            </Select>
            <Select value={region} onChange={regionChange} allowClear placeholder="城区" className="u-m-l-10" style={{width: 100}}>
                { regionList.map(e => <Option value={e.id} key={e.id}>{e.name}</Option>) }
            </Select>
            <Select value={area} onChange={areaChange} allowClear placeholder="片区" className="u-m-l-10" style={{width: 100}}>
                { areaList.map(e => <Option value={e.id} key={e.id}>{e.name}</Option>) }
            </Select>
        </div>
    )

    function cityGet(pid = 0){
        return http('city.index', {
            filter: JSON.stringify({pid}),
            op: JSON.stringify({pid: '='})
        })
    }
    function getCity(id = 0){
        cityGet(id).then(res => {
            if(res.code === 1){
                setCityList(res.data.rows)
            }
        }).catch(err=>console.log(err))
    }
    function getRegion(id = city){
        cityGet(id).then(res => {
            if(res.code === 1){
                setRegionList(res.data.rows)
            }
        })
    }
    function getArea(id = region){
        cityGet(id).then(res => {
            if(res.code === 1){
                setAreaList(res.data.rows)
            }
        })
    }
    function cityChange(id){
        setCity(id)
        setRegion()
        setArea()
        props.onChange(id)
    }
    function regionChange(id){
        setRegion(id)
        setArea()
        props.onChange(city,id)
    }
    function areaChange(id){
        setArea(id)
        props.onChange(city,region,id)
    }
}
export default City;